package com.hy.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hy.medicine.MedicineStockRecord;
import com.hy.medicine.dto.StockRecordQueryDTO;
import com.hy.medicine.vo.MedicineStockRecordVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 库存变动记录Mapper
 */
@Mapper
public interface MedicineStockRecordMapper extends BaseMapper<MedicineStockRecord> {

    /**
     * 查询库存变动记录（带药品信息）
     */
    Page<MedicineStockRecordVO> selectStockRecords(Page<?> page, @Param("dto") StockRecordQueryDTO dto);

    /**
     * 统计本月入库数量
     *
     * @return 入库总数
     */
    @Select("SELECT COALESCE(SUM(change_quantity), 0) FROM medicine_stock_record " +
            "WHERE change_type = 1 AND DATE_FORMAT(operate_time,'%Y%m') = DATE_FORMAT(NOW(),'%Y%m')")
    Integer sumMonthlyIn();

    /**
     * 统计本月出库数量
     *
     * @return 出库总数
     */
    @Select("SELECT ABS(COALESCE(SUM(change_quantity), 0)) FROM medicine_stock_record " +
            "WHERE change_type = 2 AND DATE_FORMAT(operate_time,'%Y%m') = DATE_FORMAT(NOW(),'%Y%m')")
    Integer sumMonthlyOut();

    /**
     * 批量插入变动记录
     *
     * @param records 变动记录列表
     * @return 影响行数
     */
    int insertBatch(@Param("list") List<MedicineStockRecord> records);
}
